﻿using System.Threading;

namespace Hsenl.Network {
    // 提供所有与包相关的支持
    public abstract class APacketHandler : IPacketHandler {
        private bool _isInited;
        private int _isDisposed;

        public bool IsDisposed => Volatile.Read(ref this._isDisposed) == 1;

        public void Init(Channel channel) {
            if (this._isInited)
                return;

            this._isInited = true;
            Interlocked.Exchange(ref this._isDisposed, 0);
            this.OnInit(channel);
        }

        public void Dispose() {
            if (Interlocked.CompareExchange(ref this._isDisposed, 1, 0) != 0)
                return;

            this._isInited = false;
            this.OnDisposed();
        }

        protected abstract void OnInit(Channel channel);
        protected abstract void OnDisposed();
    }
}